<?php
// +----------------------------------------------------------------------
// | 中联致远服务端框架
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.zhongliansoft.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: tony <tanyu@zhongliansoft.com>
// +----------------------------------------------------------------------

namespace app\Manage\controller;

use app\common\controller\Manage;
use app\common\model\Common as UModel;
use app\common\model\ViewGetDepts as ViewGetDeptsModel;
use app\common\model\BookApply as BookApplyModel;
use app\common\model\Manage as ManageModel;
use app\common\model\StudentInfo as StudentInfoModel;
use app\common\model\TeacherInfo as TeacherInfoModel;
use app\common\model\ViewGetTeachers as ViewGetTeachersModel;
use app\common\model\StudentType as StudentTypeModel;
use app\common\model\StudentTypeParams as StudentTypeParamsModel;
use app\common\model\StudentTypeRel as StudentTypeRelModel;
use app\common\model\PlanStudentRel as PlanStudentRelModel;
use app\common\model\Config as ConfigModel;
use think\facade\Request;
use think\facade\Log;
use think\Db;

class Student extends Manage
{
    public function index()
    {
        if(Request::isAjax())
        {
            $dep_id = input('dep_id', '');
            $specialty_id = input('specialty_id', '');
            $class_id = input('class_id', '');
            $dir = input('dir', '');
            $type_id = input('type_id', '');
            $param_id = input('param_id', '');
            $xh = input('xh', '');
            $xm = input('xm', '');
            $teacherName = input('teacherName', '');
            $status = input('status', ''); 
            $limit = input('limit', 0); 
            $page = input('page', 0);
            $index = ($page - 1) * $limit;
            // 这里直接调用SQL查询数据
            $model = new UModel();
            $list = $model->query("call getStudentList('".$dep_id."','".$specialty_id."','".$class_id."','".$dir."','".$type_id."','".$param_id."','".$xh."','".$xm."','".$teacherName."','".$status."',".$index.",".$limit.");");
    
            if(count($list) == 0){
                $re['code'] = 0;
                $re['msg'] = '';
                $re['count'] = 0;
                $re['data'] = [];
                return $re;
            }

            $re['code'] = 0;
            $re['msg'] = '';
            $re['count'] = count($list[1]);
            $re['data'] = $list[0];
            return $re;
        }

        // 如果是管理员则查询所有部门，否则查询用户所属部门
        $viewGetDeptsModel = new ViewGetDeptsModel();
        $manageModel = new manageModel();
        //if(session('manage')['id'] == $manageModel::TYPE_SUPER_ID){
        // 获取部门列表
        $dep_nameList = $viewGetDeptsModel->select();
        $this->assign('depList', $dep_nameList);
        $this->assign('bmdm', '');

        //获取类型
        $studentTypeModel = new StudentTypeModel();
        $typeList = $studentTypeModel->select();
        $this->assign('typeList', $typeList);

        // } else {
        //     $depList = [];
        //     $mgrInfo = $manageModel->where(['id' => session('manage')['id']])->find();
        //     if($mgrInfo) {
        //         $bmdm = $mgrInfo['deptId'];
        //         $bmmc = $viewGetDeptsModel->where(['bmdm' => $bmdm])->find()['bmmc'];
        //         $depList[] = ['bmdm'=> $bmdm, 'bmmc' => $bmmc];
        //         $this->assign('depList', $depList);
        //         $this->assign('bmdm', $bmdm);
        //     }
        // }

        return $this->fetch();
    }
    
    /**
     *  学生信息修改
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit()
    {
        //$this->view->engine->layout(false);
        $studentInfo = new StudentInfoModel();
        
        if(Request::isPost())
        {
            return $studentInfo->saveData(input('param.'));
        }

        $info = $studentInfo->field("a.xh, case when `a`.`dir` = 1 then '就业' when `a`.`dir` = 2 then '升学' when `a`.`dir` = 3 then '创业' end dir, c.truename as teacherName, b.xm")
            ->alias('a')
            ->join('zlzhsf.pxsdm b', 'a.xh = b.xh')
            ->leftjoin('zl_user c', 'a.teacherId = c.id')
            ->where(['a.xh' => input('param.')['xh']])
            ->find();
 
        if (!$info) {
            return error_code(10002);
        }
        
        $this->assign('xh', $info['xh']);
        $this->assign('xm', $info['xm']);
        $this->assign('dir', $info['dir']);
        $this->assign('teacherName', $info['teacherName']);
      
        $studentTypeModel = new StudentTypeModel();
        $studentTypeParamsModel = new StudentTypeParamsModel();
        // 获取学生的类型列表
        $studentTypeRelModel = new StudentTypeRelModel();
        $configModel = new ConfigModel();
        $year = $configModel->getYear();
        $season = $configModel->getSeason();

        $typeParamsList = $studentTypeRelModel->where(['plan_year' => $year, 'plan_season' => $season, 'xh' => $info['xh']])->select();
        $checkedList = [];
        foreach($typeParamsList as $val) {
            $checkedList[] = $val['type_id'].'-'.$val['param_id'];
        }
        
        $typeList = $studentTypeModel->order('sort asc')->select();
        $types = [];
		foreach ($typeList as $typeVal) {
            $types[$typeVal['id']]['id']      = $typeVal['id'];
            $types[$typeVal['id']]['name']    = $typeVal['name'];
            $paramList = $studentTypeParamsModel->where(['type_id'=>$typeVal['id']])->order('sort asc')->select();
            
            $params = [];
		    foreach ($paramList as $paramVal) {
                $params[$paramVal['id']]['id']      = $paramVal['id'];
                $params[$paramVal['id']]['name']    = $paramVal['name'];

                $key = $typeVal['id']."-".$paramVal['id'];

                if(in_array($key, $checkedList)){
                    $types[$typeVal['id']]['select'] = $paramVal['name'];
                }
            }
            $types[$typeVal['id']]['Params'] = $params;
        } 
        $this->assign('types', $types);
         
        // 根据学生当前的提交状态判定教师列表
        // 如果更改了辅导员且存在申请为领书的情况，则需要删除该学生的申请记录
        $bookApplyModel = new BookApplyModel();
        $qsInfo = $bookApplyModel->getIsqs($year, $season, $info['xh']);

        $teacherList = [];
        if($qsInfo && $qsInfo['is_qs'] == '0') {
            // 获取申请时的所在的班级
            $planStudentRelModel = new PlanStudentRelModel();
            $relInfo = $planStudentRelModel->where(['plan_code'=>$qsInfo['class_id']])->find();
            // 获取申请时学生所在班级的所有辅导员
            $teacherIdListWhere = [];
            $teacherIdListWhere[] = ['bjdm', 'eq', $relInfo['bjdm']];
            $teacherIdListWhere[] = ['teacherId', 'neq', ''];

            $teacherList = $studentInfo->field('b.id, b.mobile, b.truename')
                                ->distinct(true)
                                ->alias('a')
                                ->join('zl_user b', 'a.teacherId = b.id')
                                ->where($teacherIdListWhere)
                                ->select();
        } else {
            $viewGetTeachersModel = new ViewGetTeachersModel();
            $teacherList = $viewGetTeachersModel->select();
        }
        
        $this->assign('teacherList', $teacherList);
        return $this->fetch('edit');
    }
    
    /**
     * 导入学生信息
     * @return array|mixed
     */
    public function importStudent()
    {
        if (Request::isPost()) {
            return null;
        }
        return $this->fetch('ImportStudent');
    }

    /**
     * 导入学生类型
     * @return array|mixed
     */
    public function importStudentType()
    {
        if (Request::isPost()) {
            return null;
        }
        return $this->fetch('importStudentType');
    }

    /**
     * 按班级导入辅导员
     * @return array|mixed
     */
    public function importTeacher()
    {
        if (Request::isPost()) {
            return null;
        }
        return $this->fetch('ImportTeacher');
    }

    /**
     * 同步财务数据
     * @return array|mixed
     */
    public function sync()
    {
        $studentInfo = new StudentInfoModel();
        return $studentInfo->sync();
    }

    /**
     * 批量替换
     * @return array|mixed
     */
    public function batchReplaceIndex()
    {
        if (Request::isAjax()) {
            $dep_id = input('dep_id', '');
            $specialty_id = input('specialty_id', '');
            $class_id = input('class_id', '');
            $dir = input('dir', '');
            $teacherName = input('teacherName', '');
            $limit = input('limit', 0); 
            $page = input('page', 0);
            $index = ($page - 1) * $limit;
            // 这里直接调用SQL查询数据
            $model = new UModel();
            $list = $model->query("call getClassTeacherInfo('".$dep_id."','".$specialty_id."','".$class_id."','".$dir."','".$teacherName."',".$index.",".$limit.");");
    
            if(count($list) == 0){
                $re['code'] = 0;
                $re['msg'] = '';
                $re['count'] = 0;
                $re['data'] = [];
                return $re;
            }

            $re['code'] = 0;
            $re['msg'] = '';
            $re['count'] = count($list[1]);
            $re['data'] = $list[0];
            return $re;
        }
        // 如果是管理员则查询所有部门，否则查询用户所属部门
        $viewGetDeptsModel = new ViewGetDeptsModel();

        $dep_nameList = $viewGetDeptsModel->select();
        $this->assign('depList', $dep_nameList);
        $this->assign('bmdm', '');
        return $this->fetch('BatchReplaceIndex');
    }

    /**
     * 批量替换辅导员
     * @return array|mixed
     */
    public function batchReplaceTeacher()
    {
        if(Request::isPost())
        {
            $teacherInfo = new TeacherInfoModel();
            return $teacherInfo->batchReplaceTeacher(input('param.'));
        }

        // 如果是管理员则查询所有部门，否则查询用户所属部门
        $viewGetDeptsModel = new ViewGetDeptsModel();
        $dep_nameList = $viewGetDeptsModel->select();
        $this->assign('depList', $dep_nameList);
        $this->assign('bmdm', '');
        return $this->fetch('/student/BatchReplaceIndex');
    }
    
}
